import {
  getProductList,
  getExhibitorList,
  getProductDetail,
  getExhibitorDetail,
  getExProducts,
  getNews,
  getNewsDetail,
  getVideoList,
  postSmsCode,
  postLogin,
  postExhibitorLogin,
  getUserSelf,
  postLikeProduct,
  postLikeExhibitor,
  postLikeNews,
  postWantbuy,
  getLikeProductList,
  getLikeNewsList,
  getLikeExhibitorList,
  getWantbuyList,
  getExhibitor2021,
  getWantbuyDetail,
  postReceipt,
  getExhibitCategoryList,
  getArticleCategoryList,
  getBannerList,
  getVenues,
  getMeetingList,
  getMeetingDetail,
  getwechat,
  fetchWechatConfig,
  fetchBusinessMatchList,
  fetchBusinessMatchDetail,
  addBusinessMatchApply,
} from '../servers';

import { postExhibitor, postStaticPage } from '../servers/service';
import { Toast } from 'antd-mobile';
import { Config } from '../config';
import { CreateLoading } from '../utils/tools';
import { setToken } from '../utils/authority';
import { toTree } from '../utils/toTree';

export default {
  namespace: 'index',
  state: {
    // userInfo: {name:'www'},
    userInfo: sessionStorage.getItem('userInfo')
      ? JSON.parse(sessionStorage.getItem('userInfo'))
      : null,

    productList: [],
    productPageIndex: 0,
    productLastPage: null,
    productValue: null,

    exhibitorList: [],
    exhibitorPageIndex: 0,
    exhibitorLastPage: null,
    exhibitorValue: null,

    productDetail: null,
    exhibitorDetail: null,
    exProduct: [],

    newsList: [],
    newsPageIndex: 0,
    newsDetail: null,
    newsLastPage: null,

    videoList: [],
    loginModalShow: false,
    roleSelectModalVisible: false,
    loginTypeIndex: 0,

    wantbuyList: [],
    // wantbuyDetail: null,
    wantBuyDetail: null,

    likeProductList: [],
    likeExhibitorList: [],
    likeNewsList: [],

    exhibitor2021List: [],
    exhibitor2021PageIndex: 0,
    exhibitor2021LastPage: null,
    exhibitor2021Value: null,
    exhibitCategoryList: [],
    articleCategoryList: [],
    bannerList: [],
    adList: [],

    venues: [],

    meetingList: [],
    meetingPageIndex: 0,
    meetingDetail: null,
    meetingLastPage: null,

    wechatConfig: {},
  },
  effects: {
    *apiGetProductList({ payload, isReset }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getProductList, { ...payload }); //  sort: 'sequence,DESC'
      clearTimeout(login);
      Toast.hide();
      if (response.data) {
        const { index, list } = yield select(({ index }) => {
          return {
            index: index.productPageIndex,
            list: index.productList,
          };
        });
        if (isReset) {
          yield put({
            type: 'setState',
            payload: {
              productList: [...response.data.content],
              productPageIndex: response.data.number,
              productLastPage: response.data.totalPages,
              productValue: response.data.totalElements,
            },
          });
          return;
        } else {
          // if (list.length > 50) {
          //     list.splice(0, response.length)
          // }
          yield put({
            type: 'setState',
            payload: {
              productList: [...list, ...response.data.content],
              productPageIndex: response.data.number,
              productLastPage: response.data.totalPages,
              productValue: response.data.totalElements,
            },
          });
        }
      }
    },
    *apiGetProductDetail({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getProductDetail, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { productDetail: response.data } });
      }
    },
    *apiGetExhibitorList({ payload, isReset }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getExhibitorList, { ...payload, sort: 'sequence,DESC' });
      clearTimeout(login);
      Toast.hide();
      if (response) {
        const { index, list } = yield select(({ index }) => {
          return {
            index: index.exhibitorPageIndex,
            list: index.exhibitorList,
          };
        });
        // let newData = response.filter((vo) => (vo.status == '1'))
        if (isReset) {
          yield put({
            type: 'setState',
            payload: {
              exhibitorList: [...response.content],
              exhibitorPageIndex: response.number,
              exhibitorLastPage: response.totalPages,
              newsPageIndex: response.number,
              exhibitorValue: response.totalElements,
            },
          });
          return;
        }
        yield put({
          type: 'setState',
          payload: {
            exhibitorList: [...list, ...response.content],
            exhibitorPageIndex: response.number,
            exhibitorLastPage: response.totalPages,
            newsPageIndex: response.number,
            exhibitorValue: response.totalElements,
          },
        });
      }
    },
    *apiGetExhibitorDetail({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getExhibitorDetail, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { exhibitorDetail: response.data } });
      }
    },
    *apiGetExProducts({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getExProducts, payload);
      clearTimeout(login);
      Toast.hide();
      // console.log(response, 'response')
      if (response) {
        yield put({ type: 'setState', payload: { exProduct: response.data.content } });
      }
    },
    *apiGetNews({ payload, isReset }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getNews, payload);
      clearTimeout(login);
      Toast.hide();
      // console.log(isReset, 'isReset')
      if (response) {
        const { index, list } = yield select(({ index }) => {
          return {
            index: index.newsPageIndex,
            list: index.newsList,
          };
        });
        if (isReset) {
          yield put({
            type: 'setState',
            payload: {
              newsList: [...response.data.content],
              newsLastPage: response.data.totalPages,
              newsPageIndex: response.data.number,
            },
          });
          return;
        }
        yield put({
          type: 'setState',
          payload: {
            newsList: [...list, ...response.data.content],
            newsLastPage: response.data.totalPages,
            newsPageIndex: response.data.number,
          },
        });
      }
    },
    *apiGetNewsDetail({ payload }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getNewsDetail, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { newsDetail: response.data } });
      }
    },
    *apiGetVideoList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getVideoList, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { videoList: response.data } });
      }
    },
    *apiGetSmsCode({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postSmsCode, payload);
      clearTimeout(login);
      Toast.hide();
      if (response.error && response.error != 0) {
        callback(false);
      } else {
        callback(true);
      }
    },
    *apiLogin({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postLogin, payload);
      clearTimeout(login);
      Toast.hide();
      if (response.data.token) {
        callback(true);
        yield put({ type: 'login', payload: response });
      } else {
        callback(false);
      }
    },
    *apiExhibitorLogin({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postExhibitorLogin, payload);
      clearTimeout(login);
      Toast.hide();
      if (response.data.token) {
        callback(true);
        yield put({ type: 'login', payload: response });
      } else {
        callback(false);
      }
    },
    *apiGetUserSelf({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getUserSelf, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        if (response.error) {
          return;
        }
        yield put({ type: 'setState', payload: { userInfo: response.data } });
      }
    },
    *apiPostLikeProduct({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postLikeProduct, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        if (callback) {
          callback();
        }
        // console.log(response, 'response');
        // yield put({ type: 'updatedProductLike', payload: { response } });
      }
    },
    *apiPostLikeExhibitor({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postLikeExhibitor, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        if (callback) {
          callback();
        }
        // yield put({ type: 'updatedExhibitorLike', payload: { response } });
      }
    },
    *apiPostLikeNews({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postLikeNews, payload);
      clearTimeout(login);
      Toast.hide();
      // console.log(response, 'response')
      if (response) {
        if (callback) {
          callback();
        }
        yield put({ type: 'updatedNewsLike', payload: { data: payload } });
      }
    },
    *apiPostWantbuy({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postWantbuy, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        callback(true);
      }
    },
    *apiGetLikeProductList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getLikeProductList, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        yield put({ type: 'setState', payload: { likeProductList: response.data.content } });
      }
    },
    *apiGetLikeExhibitorList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getLikeExhibitorList, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        yield put({ type: 'setState', payload: { likeExhibitorList: response.data.content } });
      }
    },
    *apiGetLikeNewsList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getLikeNewsList, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        response?.data?.content.map((item) => {
          item.object.ifCollect = true;
        });
        // console.log(response)
        yield put({ type: 'setState', payload: { likeNewsList: response.data.content } });
      }
    },
    *apiGetWantbuyList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getWantbuyList, payload);
      Toast.hide();
      clearTimeout(login);
      if (response.error) {
        return;
      }
      if (response) {
        // console.log(response, 'apiGetWantbuyList')
        yield put({ type: 'setState', payload: { wantbuyList: response.data.content } });
      }
    },
    *apiGetWantbuyDetail({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getWantbuyDetail, payload);
      Toast.hide();
      clearTimeout(login);
      if (response.error && response.error != 0) {
        return;
      }
      if (response) {
        yield put({ type: 'setState', payload: { wantBuyDetail: response.data } });
      }
    },
    *apiGetExhibitor2021({ payload, isReset }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getExhibitorList, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        const { index, list } = yield select(({ index }) => {
          return {
            index: index.exhibitor2021PageIndex,
            list: index.exhibitor2021List,
          };
        });
        // let newData = response.filter((vo) => (vo.status == '1'))
        if (isReset) {
          yield put({
            type: 'setState',
            payload: {
              exhibitor2021List: [...response.content],
              exhibitor2021PageIndex: response.number,
              exhibitor2021LastPage: response.totalPages,
              exhibitor2021Value: response.totalElements,
            },
          });
          return;
        }
        yield put({
          type: 'setState',
          payload: {
            exhibitor2021List: [...list, ...response.content],
            exhibitor2021PageIndex: response.number,
            exhibitor2021LastPage: response.totalPages,
            exhibitor2021Value: response.totalElements,
          },
        });
      }
    },
    *apiPostReceipt({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postReceipt, payload);
      Toast.hide();
      clearTimeout(login);
      if (response.error) {
        Toast.fail('数据提交失败，请检查数据是否填写完整');
        callback(false);
        return;
      }
      if (response) {
        Toast.success('数据提交成功');
        callback(true);
      }
    },
    *apiGetExhibitCategoryList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getExhibitCategoryList, payload.data);
      const exhibitCategoryList = response.data.toTree().slice(0, 11);
      console.log(exhibitCategoryList);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { exhibitCategoryList: exhibitCategoryList } });
      }
    },
    *apiGetArticleCategoryList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getArticleCategoryList, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { articleCategoryList: response.data } });
      }
    },
    *apiGetBannerList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getBannerList, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { bannerList: response.data } });
      }
    },
    *apiGetMeetingList({ payload, isReset }, { call, put, select }) {
      const login = CreateLoading();
      const response = yield call(getMeetingList, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        const { index, list } = yield select(({ index }) => {
          return {
            index: index.meetingPageIndex,
            list: index.meetingList,
          };
        });
        console.log('isReset', isReset);
        // debugger;
        if (isReset) {
          yield put({
            type: 'setState',
            payload: {
              meetingList: response.data.content,
              meetingLastPage: response.data.totalPages,
              meetingPageIndex: response.data.number,
            },
          });
          return;
        } else {
          yield put({
            type: 'setState',
            payload: {
              meetingList: [...list, ...response.data.content],
              meetingLastPage: response.data.totalPages,
              meetingPageIndex: response.data.number,
            },
          });
        }
      }
    },
    *apiGetMeetingDetail({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getMeetingDetail, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        const detail = response.data || {};
        detail.content &&
          (detail.content = detail.content.replace(/\<img/gi, '<img class="richtext-img" '));
        detail.contentEn &&
          (detail.contentEn = detail.contentEn.replace(/\<img/gi, '<img class="richtext-img" '));
        console.log(detail);
        yield put({
          type: 'setState',
          payload: {
            meetingDetail: response.data,
          },
        });
      }
    },
    *apiGetBusinessMatchList({ payload }, { call, put }) {
      try {
        const login = CreateLoading();
        const response = yield call(fetchBusinessMatchList, payload);
        clearTimeout(login);
        Toast.hide();
        if (response) {
          yield put({
            type: 'setState',
            payload: {
              businessMatchList: response,
            },
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
    *apiGetBusinessMatchDetail({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(fetchBusinessMatchDetail, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({
          type: 'setState',
          payload: {
            businessMatchDetail: response,
          },
        });
      }
    },
    *apiAddBusinessMatchApply({ payload, callback, errCallback }, { call, put }) {
      debugger;
      try {
        Toast.loading('申请已提交，请耐心等待', 0);
        const response = yield call(addBusinessMatchApply, payload);
        Toast.hide();
        debugger;
        if (response.error) {
          Toast.fail('您的申请已被预约，请选择其他时间段。敬请谅解！');
          setTimeout(() => {
            errCallback && errCallback();
          }, 3000);
          return;
        }
        if (response) {
          // Toast.success('数据提交成功');
          callback && callback();
        }
      } catch (error) {
        debugger;
        errCallback && errCallback();
      }
    },
    *apiGetAdList({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getBannerList, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { adList: response.data } });
      }
    },
    *apiGetWechatConfig({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(fetchWechatConfig, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { wechatConfig: response } });
      }
    },
    *getVenues({ payload }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(getVenues, payload);
      clearTimeout(login);
      Toast.hide();
      if (response) {
        yield put({ type: 'setState', payload: { venues: response.data } });
      }
    },
    *apiPostExhibitor({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postExhibitor, payload);
      Toast.hide();
      clearTimeout(login);
      if (response.error) {
        Toast.fail('提交失败，请检查数据是否填写完整');
        callback(false);
        return;
      }
      if (response) {
        Toast.success('编辑成功');
        callback(true);
      }
    },
    *apiPostStaticPage({ payload, callback }, { call, put }) {
      const login = CreateLoading();
      const response = yield call(postStaticPage, payload);
      Toast.hide();
      clearTimeout(login);
      if (response) {
        callback(true);
      }
    },
  },
  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    login(state, { payload }) {
      payload && payload.data && payload.data.token && setToken(payload.data.token);

      console.log(payload.data);
      sessionStorage.setItem('userInfo', JSON.stringify(payload.data));

      return {
        ...state,
        userInfo: payload.data,
        user: payload.data.user,
        exhibitor: payload.data.exhibitor,
      };
    },
    updatedNewsLike(state, { payload }) {
      const { data } = payload;
      const { newsList, likeNewsList } = state;

      let arr = [];
      if (data.operateType === 1) {
        arr = JSON.parse(JSON.stringify(newsList));
        arr.map((item) => {
          if (item.id == data.objectId) {
            item.ifCollect = !item.ifCollect;
          }
        });
        return {
          ...state,
          newsList: [...arr],
        };
      } else {
        arr = JSON.parse(JSON.stringify(likeNewsList));
        arr.map((item) => {
          console.log(item);
          if (item.object.id == data.objectId) {
            item.object.ifCollect = !item.object.ifCollect;
          }
        });
        return {
          ...state,
          likeNewsList: [...arr],
        };
      }
    },
    updatedProductLike(state, { payload }) {
      const { response } = payload;
      const { productDetail } = state;
      if (response.UserProduct === 'DELETE') {
        productDetail.likeCount = productDetail.likeCount - 1;
      } else {
        productDetail.likeCount = productDetail.likeCount + 1;
      }

      return {
        ...state,
      };
    },
    updatedExhibitorLike(state, { payload }) {
      const { response } = payload;
      const { exhibitorDetail } = state;
      if (response.UserExhibitor === 'DELETE') {
        exhibitorDetail.likeCount = exhibitorDetail.likeCount - 1;
      } else {
        exhibitorDetail.likeCount = exhibitorDetail.likeCount + 1;
      }
      return {
        ...state,
      };
    },
  },
};
